/*
Author : Nguyen Van Ty
Email  : ngvanty03@gmail.com
Date   : 12/13/2010 

*/

using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Common;
using BusinessObject;
using Utility;
using System.Xml;
namespace DataAccessLayer
{
    /// <summary>
    /// Define UserProfileDaoBase class. This class user for DataAccessLayer, contain 4 function Insert, Update, Search, Delete.
    /// If you want add new function, you must define in UserProfileDao class , not here.
    /// </summary>
    public class UserProfileDaoBase
    {
        private static ILog logger = null;
        #region Constructor
        /// <summary>
        /// Define Constructor.
        /// </summary>
        public UserProfileDaoBase() { }
        static UserProfileDaoBase()
        {
            //Init logger.
            logger = LoggingUtility.GetLogger(typeof(UserProfileDaoBase).FullName);
        }
        #endregion
        /// <summary>
        /// Read data from IDataReader, convert to UserProfile Object.
        /// </summary>
        protected static UserProfile GetUserProfileByDataReader(IDataReader reader)
        {
            String methodName = "GetUserProfileByDataReader";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            try
            {
                UserProfile result = new UserProfile();
                //read UserId field data.

                result.UserId = ManagerDao.GetguidDataFromDataReader(reader, "UserId");

                //read Name field data.

                result.Name = ManagerDao.GetstringDataFromDataReader(reader, "Name");

                //read Address field data.

                result.Address = ManagerDao.GetstringDataFromDataReader(reader, "Address");

                //read Phone field data.

                result.Phone = ManagerDao.GetstringDataFromDataReader(reader, "Phone");

                //read Gender field data.

                result.Gender = ManagerDao.GetintDataFromDataReader(reader, "Gender");

                //read BirthDay field data.

                result.BirthDay = ManagerDao.GetdatetimeDataFromDataReader(reader, "BirthDay");

                //read CreatedBy field data.

                result.CreatedBy = ManagerDao.GetstringDataFromDataReader(reader, "CreatedBy");

                //read CreatedDate field data.

                result.CreatedDate = ManagerDao.GetdatetimeDataFromDataReader(reader, "CreatedDate");

                //read LastUpdatedBy field data.

                result.LastUpdatedBy = ManagerDao.GetstringDataFromDataReader(reader, "LastUpdatedBy");

                //read LastUpdatedDate field data.

                result.LastUpdatedDate = ManagerDao.GetdatetimeDataFromDataReader(reader, "LastUpdatedDate");

                return result;
            }
            catch (Exception e)
            {
                // write error to log file.
                logger.Error(methodName, e);
                return null;
            }
        }
        /// <summary>
        /// Define function Insert for UserProfile Object.
        /// </summary>
        /// <param name="obj">Object Insert.</param>
        /// <returns>
        ///    True: Successfull.
        ///    False: Process Error.
        ///</returns>
        public static bool Insert(UserProfile obj)
        {
            bool result = false;
            String methodName = "InsertUserProfile";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            DbCommand cmd = ManagerDao.GetStoredProcCommand("spInsertUserProfile");

            //Add value "UserId"  paramater.
            ManagerDao.AddInParameter(cmd, "UserId", DbType.Guid, obj.UserId);
            //Add value "Name"  paramater.
            ManagerDao.AddInParameter(cmd, "Name", DbType.String,
                ConvertValueObject.CastObjValueToInsertDB(obj.Name));
            //Add value "Address"  paramater.
            ManagerDao.AddInParameter(cmd, "Address", DbType.String,
                ConvertValueObject.CastObjValueToInsertDB(obj.Address));
            //Add value "Phone"  paramater.
            ManagerDao.AddInParameter(cmd, "Phone", DbType.AnsiString,
                ConvertValueObject.CastObjValueToInsertDB(obj.Phone));
            //Add value "Gender"  paramater.
            ManagerDao.AddInParameter(cmd, "Gender", DbType.Int32,
                ConvertValueObject.CastObjValueToInsertDB(obj.Gender));
            //Add value "BirthDay"  paramater.
            ManagerDao.AddInParameter(cmd, "BirthDay", DbType.DateTime,
                ConvertValueObject.CastObjValueToInsertDB(obj.BirthDay));
            //Add value "CreatedBy"  paramater.
            ManagerDao.AddInParameter(cmd, "CreatedBy", DbType.String,
                ConvertValueObject.CastObjValueToInsertDB(obj.CreatedBy));
            //Add value "CreatedDate"  paramater.
            ManagerDao.AddInParameter(cmd, "CreatedDate", DbType.DateTime,
                ConvertValueObject.CastObjValueToInsertDB(obj.CreatedDate));
            //Add value "LastUpdatedBy"  paramater.
            ManagerDao.AddInParameter(cmd, "LastUpdatedBy", DbType.String,
                ConvertValueObject.CastObjValueToInsertDB(obj.LastUpdatedBy));
            //Add value "LastUpdatedDate"  paramater.
            ManagerDao.AddInParameter(cmd, "LastUpdatedDate", DbType.DateTime,
                ConvertValueObject.CastObjValueToInsertDB(obj.LastUpdatedDate));
            //add paramater store return value.        
            ManagerDao.AddParameter(cmd, "returnValue", DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
            try
            {
                ManagerDao.ExecuteNonQuery(cmd);
                int id = (int)ManagerDao.GetParameterValue(cmd, "returnValue");
                if (id > 0)//Successfull.
                {
                    result = true;
                }
                else//Error.
                {
                    result = false;
                }
            }
            catch (Exception e)
            {
                //write error message to log file.
                logger.Error(methodName, e);
                result = false;
            }
            return result;
        }

        /// <summary>
        /// Define function Update for UserProfile Object.
        /// </summary>
        /// <param name="obj">Object Update.</param>
        /// <returns>
        ///    True: Successfull.
        ///    False: Process Error.
        ///</returns>
        public static bool Update(UserProfile obj)
        {
            bool result = false;
            String methodName = "UpdateUserProfile";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            DbCommand cmd = ManagerDao.GetStoredProcCommand("spUpdateUserProfile");


            //Add value "UserId"  paramater.
            ManagerDao.AddInParameter(cmd, "UserId", DbType.Guid, ConvertValueObject.CastObjValueToInsertDB(obj.UserId));
            //Add value "Name"  paramater.
            ManagerDao.AddInParameter(cmd, "Name", DbType.String, ConvertValueObject.CastObjValueToInsertDB(obj.Name));
            //Add value "Address"  paramater.
            ManagerDao.AddInParameter(cmd, "Address", DbType.String, ConvertValueObject.CastObjValueToInsertDB(obj.Address));
            //Add value "Phone"  paramater.
            ManagerDao.AddInParameter(cmd, "Phone", DbType.AnsiString, ConvertValueObject.CastObjValueToInsertDB(obj.Phone));
            //Add value "Gender"  paramater.
            ManagerDao.AddInParameter(cmd, "Gender", DbType.Int32, ConvertValueObject.CastObjValueToInsertDB(obj.Gender));
            //Add value "BirthDay"  paramater.
            ManagerDao.AddInParameter(cmd, "BirthDay", DbType.DateTime, ConvertValueObject.CastObjValueToInsertDB(obj.BirthDay));
            //Add value "CreatedBy"  paramater.
            ManagerDao.AddInParameter(cmd, "CreatedBy", DbType.String, ConvertValueObject.CastObjValueToInsertDB(obj.CreatedBy));
            //Add value "CreatedDate"  paramater.
            ManagerDao.AddInParameter(cmd, "CreatedDate", DbType.DateTime, ConvertValueObject.CastObjValueToInsertDB(obj.CreatedDate));
            //Add value "LastUpdatedBy"  paramater.
            ManagerDao.AddInParameter(cmd, "LastUpdatedBy", DbType.String, ConvertValueObject.CastObjValueToInsertDB(obj.LastUpdatedBy));
            //Add value "LastUpdatedDate"  paramater.
            ManagerDao.AddInParameter(cmd, "LastUpdatedDate", DbType.DateTime, ConvertValueObject.CastObjValueToInsertDB(obj.LastUpdatedDate));
            // add parameter store return value.
            ManagerDao.AddParameter(cmd, "returnValue", DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
            try
            {
                ManagerDao.ExecuteNonQuery(cmd);
                int rows = (int)ManagerDao.GetParameterValue(cmd, "returnValue");
                if (rows == 1)//Successfull.
                {
                    result = true;
                }
                else//Error.
                {
                    result = false;
                }

            }
            catch (Exception e)
            {
                //write error Message to log file.
                logger.Error(methodName, e);
                result = false;
            }
            return result;
        }
        /// <summary>
        /// Get Data UserProfile object. 
        /// </summary>
        /// <param name="userId" >This is primary key to get data.</param>
        /// <returns>UserProfile object.</returns>

        public static UserProfile Get(Guid userId)
        {
            String methodName = "GetUserProfile";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            try
            {
                UserProfile result = null;
                DbCommand dbCommnand = ManagerDao.GetStoredProcCommand("spGetUserProfile");
                //Add value "UserId"  paramater.
                ManagerDao.AddInParameter(dbCommnand, "UserId", DbType.Guid, userId);
                IDataReader reader = ManagerDao.ExecuteReader(dbCommnand);
                if (reader.Read())
                {
                    result = GetUserProfileByDataReader(reader);

                }
                reader.Close();
                return result;
            }
            catch (System.Exception e)
            {
                //write error message to log file.
                logger.Error("Get", e);
                return null;
            }
        }
        /// <summary>
        /// Get All UserProfile object from table UserProfile.
        /// </summary>
        /// <returns>List UserProfile object.</returns>
        public static List<UserProfileResult> GetAll()
        {
            String methodName = "GetAll";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }

            try
            {
                List<UserProfileResult> listUserProfile = new List<UserProfileResult>();
                DbCommand dbCommand = ManagerDao.GetStoredProcCommand("spGetAllUserProfile");

                using (IDataReader reader = ManagerDao.ExecuteReader(dbCommand))
                {
                    while (reader.Read())
                    {
                        listUserProfile.Add(GetUserProfileResultByDataReader(reader));
                    }
                    reader.Close();
                }

                return listUserProfile;
            }
            catch (Exception ex)
            {
                //write error message to log file.
                logger.Error(methodName, ex);
                return null;
            }
        }

        /// <summary>
        /// Search UserProfile object in table UserProfile with condition is t object.
        /// </summary>
        /// <param name="t">Condition for Search.</param>       
        /// <param name="totalRow">  total records in this table.</param>
        /// <returns>List UserProfileResult object.</returns>
        public static List<UserProfileResult> SearchUserProfileSomeCondition(UserProfile t)
        {
            String methodName = "SearchUserProfileSomeCondition";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }

            try
            {
                List<UserProfileResult> listUserProfile = new List<UserProfileResult>();
                DbCommand cmd = ManagerDao.GetStoredProcCommand("spSearchUserProfileByCondition");
                ManagerDao.AddInParameter(cmd, "Condition", DbType.String, ConvertValueObject.CastObjValueToInsertDB(t.Condition));

                //Add value ApplicationName  paramater.
                ManagerDao.AddInParameter(cmd, "ApplicationName", DbType.String,t.ApplicationName);

                //Add value PageIndex  paramater.
                ManagerDao.AddInParameter(cmd, "PageIndex", DbType.Int32, t.ObjectPaging.PageIndex);
                //Add value PageSize  paramater.
                ManagerDao.AddInParameter(cmd, "PageSize", DbType.Int32, t.ObjectPaging.PageSize);
                //Add value SortField  paramater.
                ManagerDao.AddInParameter(cmd, "SortField", DbType.String, t.ObjectSortOrder.SortField);
                //Add value SortExpression  paramater.
                ManagerDao.AddInParameter(cmd, "SortExpression", DbType.String, t.ObjectSortOrder.SortExpression);
                using (IDataReader reader = ManagerDao.ExecuteReader(cmd))
                {
                    while (reader.Read())
                    {
                        listUserProfile.Add(GetUserProfileResultByDataReader(reader));
                        if (t.ToltalRow <= 0)
                            t.ToltalRow = ManagerDao.Getint32DataFromDataReader(reader, "TotalRow");
                    }

                    reader.Close();
                }

                return listUserProfile;
            }
            catch (Exception ex)
            {
                //write error message to log file.
                logger.Error(methodName, ex);
                return null;
            }
        }
        /// <summary>
        /// Delete UserProfile object. 
        /// </summary>
        /// <param name="UserId" >This is primary key to delete.</param>
        /// <returns>True/False.</returns>

        public static bool Delete(Guid UserId)
        {
            String methodName = "DeleteUserProfile";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }

            try
            {
                DbCommand dbCommand = ManagerDao.GetStoredProcCommand("spDeleteUserProfile");
                //Add value "UserId"  paramater.
                ManagerDao.AddInParameter(dbCommand, "UserId", DbType.Guid, UserId);
                //Add value returnValue  paramater.
                ManagerDao.AddParameter(dbCommand, "returnValue", DbType.Int32, ParameterDirection.ReturnValue, string.Empty, DataRowVersion.Default, null);
                try
                {
                    ManagerDao.ExecuteNonQuery(dbCommand);
                    int parameterValue = (int)ManagerDao.GetParameterValue(dbCommand, "returnValue");
                    if (parameterValue == 1)
                    {
                        return true;
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                return false;
            }
            catch (Exception e)
            {
                //write error message to log file.
                logger.Error(methodName, e);
                return false;
            }
        }
        /// <summary>
        /// Read data from IDataReader, convert to UserProfileResult Object.
        /// </summary>
        private static UserProfileResult GetUserProfileResultByDataReaderByLanguage(IDataReader reader, string LanguageId)
        {
            String methodName = "GetUserProfileResultByDataReader";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            try
            {
                UserProfileResult result = new UserProfileResult();
                //read UserId field data.
                result.UserId = ManagerDao.GetguidDataFromDataReader(reader, "UserId");

                //read Name field data.
                result.Name = ManagerDao.GetstringDataFromDataReader(reader, "Name");

                //read Address field data.
                result.Address = ManagerDao.GetstringDataFromDataReader(reader, "Address");

                //read Phone field data.
                result.Phone = ManagerDao.GetstringDataFromDataReader(reader, "Phone");

                //read Gender field data.
                result.Gender = ManagerDao.GetintDataFromDataReader(reader, "Gender");

                //read BirthDay field data.
                result.BirthDay = ManagerDao.GetdatetimeDataFromDataReader(reader, "BirthDay");

                //read CreatedBy field data.
                result.CreatedBy = ManagerDao.GetstringDataFromDataReader(reader, "CreatedBy");

                //read CreatedDate field data.
                result.CreatedDate = ManagerDao.GetdatetimeDataFromDataReader(reader, "CreatedDate");

                //read LastUpdatedBy field data.
                result.LastUpdatedBy = ManagerDao.GetstringDataFromDataReader(reader, "LastUpdatedBy");

                //read LastUpdatedDate field data.
                result.LastUpdatedDate = ManagerDao.GetdatetimeDataFromDataReader(reader, "LastUpdatedDate");

                return result;
            }
            catch (Exception e)
            {
                // write error to log file.
                logger.Error(methodName, e);
                return null;
            }
        }
        /// <summary>
        /// Read data from IDataReader, convert to UserProfileResult Object.
        /// </summary>
        private static UserProfileResult GetUserProfileResultByDataReader(IDataReader reader)
        {
            String methodName = "GetUserProfileResultByDataReader";
            if (logger.IsDebugEnabled)
            {
                LoggingUtility.logMethodEntry(logger, methodName);
            }
            try
            {
                UserProfileResult result = new UserProfileResult();
                //read UserId field data.
                result.UserId = ManagerDao.GetguidDataFromDataReader(reader, "UserId");

                //read Name field data.
                result.Name = ManagerDao.GetstringDataFromDataReader(reader, "Name");

                //read Address field data.
                result.Address = ManagerDao.GetstringDataFromDataReader(reader, "Address");

                //read Phone field data.
                result.Phone = ManagerDao.GetstringDataFromDataReader(reader, "Phone");

                //read Gender field data.
                result.Gender = ManagerDao.GetintDataFromDataReader(reader, "Gender");

                //read BirthDay field data.
                result.BirthDay = ManagerDao.GetdatetimeDataFromDataReader(reader, "BirthDay");

                //read CreatedBy field data.
                result.CreatedBy = ManagerDao.GetstringDataFromDataReader(reader, "CreatedBy");

                //read CreatedDate field data.
                result.CreatedDate = ManagerDao.GetdatetimeDataFromDataReader(reader, "CreatedDate");

                //read LastUpdatedBy field data.
                result.LastUpdatedBy = ManagerDao.GetstringDataFromDataReader(reader, "LastUpdatedBy");

                //read LastUpdatedDate field data.
                result.LastUpdatedDate = ManagerDao.GetdatetimeDataFromDataReader(reader, "LastUpdatedDate");

                return result;
            }
            catch (Exception e)
            {
                // write error to log file.
                logger.Error(methodName, e);
                return null;
            }
        }

    }
}